import BaseTable from '@/components/base/BaseTable';
import { getList as getEnsureBaseList } from '@/pages/repair/EnsureBaseInfo/api';
import { getList as getEnsureTypeList } from '@/pages/repair/EnsureType/api';
import { useRequest } from '@/utils/request';
import { formateDate } from '@/utils/time';
import { Alert, Button, message } from 'antd';
import { FC, useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { getEnsureList, saveEnsure } from '../../api';

const TypeTable = styled(BaseTable)`
  .ant-checkbox-wrapper-disabled {
    display: none;
  }
`;
const EnsurePlanInfo: FC<{
  title?: string;
  raSystemId?: string;
  raExtensionId?: string;
  keyPartsModelId?: string;
  structureId: string;
}> = (props) => {
  const { title, structureId, raSystemId, raExtensionId, keyPartsModelId } = props;
  const [selectedList, setSelectList] = useState<Record<string, string[]>>({});
  const oldSelectedList = useRef<Record<string, string[]>>({});
  const [activeEnsureBaseId, setActiveEnsureBaseId] = useState<string>();
  const getEnusre = useRequest(getEnsureList, {
    manual: true,
    onSuccess(data) {
      const { ensureBaseList = [] } = data;
      const map: Record<string, string[]> = {};
      ensureBaseList.forEach((e) => {
        map[e.id] = e.typeIdList;
      });
      oldSelectedList.current = JSON.parse(JSON.stringify(map));
      setSelectList(map);
    }
  });
  useEffect(() => {
    setSelectList({});
    oldSelectedList.current = {};
    setActiveEnsureBaseId('');
    getEnusre.run({ structureId });
  }, [structureId]);
  const save = useRequest(saveEnsure, {
    manual: true,
    onSuccess() {
      getEnusre.run({ structureId });
    }
  });
  return (
    <div>
      <h3>{title} 保障计划编辑</h3>
      <div style={{ display: 'flex' }}>
        <div style={{ width: '50%' }}>
          <BaseTable
            rowKey='id'
            headerTitle='保障基础信息选择'
            params={{ keyPartsModelId, raSystemId, raExtensionId }}
            request={getEnsureBaseList}
            height={200}
            columns={[
              {
                dataIndex: 'name',
                title: '保障名称'
              },
              {
                title: '已绑定类型数',
                renderText: (record) => {
                  const list = selectedList[record.id];
                  return list ? list.length : 0;
                }
              }
            ]}
            onRow={(record) => {
              return {
                onClick() {
                  setActiveEnsureBaseId(record.id);
                }
              };
            }}
            tableAlertRender={false}
            rowSelection={{
              type: 'radio',
              selectedRowKeys: activeEnsureBaseId ? [activeEnsureBaseId] : [],
              onChange(keys) {
                setActiveEnsureBaseId(keys[0] as string);
              }
            }}
          />
        </div>
        <div style={{ width: '50%' }}>
          {activeEnsureBaseId ? (
            <TypeTable
              headerTitle='保障类型选择'
              expandable={{
                childrenColumnName: 'resList'
              }}
              height={200}
              rowKey='id'
              tableAlertRender={false}
              rowSelection={{
                selectedRowKeys: activeEnsureBaseId ? selectedList[activeEnsureBaseId] : [],
                onChange(keys, selectRows) {
                  if (activeEnsureBaseId) {
                    const selectKeys: string[] = [];
                    selectRows.forEach((i) => {
                      if (i.parentId) {
                        selectKeys.push(i.id);
                      } else {
                        i.resList.forEach((r: { id: string }) => {
                          selectKeys.push(r.id);
                        });
                      }
                    });
                    setSelectList({
                      ...selectedList,
                      [activeEnsureBaseId]: [...new Set(selectKeys)]
                    });
                  }
                },
                getCheckboxProps(record) {
                  return {
                    disabled: !record.parentId
                  };
                }
              }}
              request={getEnsureTypeList}
              columns={[
                {
                  dataIndex: 'name',
                  title: '名称'
                },
                {
                  dataIndex: 'cycle',
                  title: '保障周期',
                  renderText: (text) => {
                    const date = formateDate(text, 2);
                    return date.value ? `${date.value} ${date.unit}` : undefined;
                  }
                },
                {
                  dataIndex: 'remarks',
                  title: '描述'
                }
              ]}
            />
          ) : (
            <Alert type='warning' message='请先选择保障基础信息' />
          )}
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <Button
          type='primary'
          onClick={() => {
            const ensureBaseList: {
              id: string;
              createTypeIdList: string[];
              deleteTypeIdList: string[];
            }[] = [];
            const oldList = oldSelectedList.current;
            const keys = Object.keys(selectedList);
            keys.forEach((key) => {
              const oldSelected = oldList[key];
              const createTypeIdList: string[] = selectedList[key];
              const deleteTypeIdList: string[] = [];
              if (oldSelected) {
                oldSelected.forEach((i) => {
                  const index = createTypeIdList.findIndex((k) => i === k);
                  if (index !== -1) {
                    createTypeIdList.splice(index, 1);
                  } else {
                    deleteTypeIdList.push(i);
                  }
                });
              }
              if (createTypeIdList.length > 0 || deleteTypeIdList.length > 0) {
                ensureBaseList.push({
                  id: key,
                  createTypeIdList,
                  deleteTypeIdList
                });
              }
            });
            if (ensureBaseList.length > 0) {
              save.run({ ensureBaseList, structureId });
            } else {
              message.warning('请先添加或移除保障类型后保存');
            }
          }}
          loading={save.loading}
        >
          保存
        </Button>
      </div>
    </div>
  );
};

export default EnsurePlanInfo;
